﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KsMusic
{
    public class ListViewImageHelper
    {
        //无需改动
        private const int LVM_FIRST = 0x1000;
        private const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;
        private const int LVS_EX_SUBITEMIMAGES = 0x0002;
        private const int LVIF_TEXT = 0x0001;
        private const int LVIF_IMAGE = 0x0002;
        private const int LVM_SETITEM = LVM_FIRST + 6;
        private struct LV_ITEM
        {
            public uint mask;//显示内容？
            public int iItem;//行号
            public int iSubItem;//列号
            public uint state;//状态？
            public uint stateMask;//状态掩码？
            public IntPtr pszText;//文字
            public int cchTextMax;
            public int iImage;//图片索引号
            public IntPtr lParam;
        }
        [DllImport("user32.dll")]
        static extern int SendMessage(IntPtr hwnd, int msg, int wParam, int lParam);
        [DllImport("user32.dll", SetLastError = true)]
        static extern int SendMessage(IntPtr hwnd, int msg, int wParam, ref LV_ITEM lParam);
        //显示图片
        public void ShowImage(ListView lv,//listView
                            int i,//行，索引
                            int j,//列，索引
                            ImageList il,//图片列表控件
                            int index)//图片索引
        {
            SendMessage(lv.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_SUBITEMIMAGES, LVS_EX_SUBITEMIMAGES);//要先加这个，要不然图片暂时显示不出来，得要一个事件来触发
            //显示图片
            LV_ITEM lvitem = new LV_ITEM();//实例化LV_ITEM结构           
            lvitem.mask = LVIF_TEXT | LVIF_IMAGE;//设置显示内容，文本+图片
            lvitem.iItem = i;//设置行号
            lvitem.iSubItem = j;//设置列
            lv.SmallImageList = il;//设置listView的SmallImageList
            lvitem.iImage = index;//设置图片索引
            //和图片一起显示的文字，可以指定，不一定是原来位置的,也可以不启用
            if (lv.Items[i].SubItems[j].Text != null)//不为空，则赋值，使其和图片一起显示出来
            {
                lvitem.pszText = Marshal.StringToHGlobalAnsi(lv.Items[i].SubItems[j].Text);
            }

            SendMessage(lv.Handle, LVM_SETITEM, 0, ref lvitem);//发送，并返回
        }
    }
}
